package com.apexwear.apexutils.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.apex.bluetooth.callback.DeviceBugCallback;
import com.apex.bluetooth.model.EABleReadDebug;
import com.apexwear.apexutils.R;
import com.apexwear.apexutils.adapter.AdapterPagesList;
import com.apexwear.apexutils.api.OnPositiveClickListener;
import com.apexwear.apexutils.common.Constant;
import com.apexwear.apexutils.databinding.ActivityMainBinding;
import com.apexwear.apexutils.dialog.ChangeMacDialog;
import com.apexwear.apexutils.model.Device;
import com.apexwear.apexutils.service.BluetoothService;
import com.apexwear.apexutils.utils.FileUtils;
import com.apexwear.apexutils.utils.PermissionUtils;
import com.apexwear.apexutils.utils.ShowToast;
import com.cazaea.sweetalert.SweetAlertDialog;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding dataBinding;
    final String TAG = this.getClass().getSimpleName();
    ReceiveWatchInfo receiveWatchInfo;
    private BluetoothService mainService;
    ServiceConnection sconnection;
    LogContent logContent;
    ChangeMacDialog changeMacDialog;
    volatile boolean isResume;
    AdapterPagesList adapterPagesList;
    volatile boolean isConnect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isResume = true;
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        dataBinding.scanBlue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionUtils.checkLocationPermission(MainActivity.this)) {
                    PermissionUtils.requestLocationPermission(MainActivity.this);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        if (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                            requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN}, 0x80);
                        } else {
                            if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                                requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 0x81);
                            } else {
                                startActivity(new Intent(MainActivity.this, QRActivity.class));
                            }
                        }
                    } else {
                        startActivity(new Intent(MainActivity.this, QRActivity.class));
                    }
                }
            }
        });
        if (receiveWatchInfo == null) {
            receiveWatchInfo = new ReceiveWatchInfo();
            IntentFilter intentFilter = new IntentFilter(Constant.CONNECT_BROADCAST);
            intentFilter.addAction(Constant.CONNECT_STATE_BROADCAST);
            intentFilter.addAction(Constant.UNBIND_BROADCAST);
            intentFilter.addAction(Constant.EXIT_TEST_STATE_BROADCAST);
            intentFilter.addAction(Constant.ENTRY_TEST_STATE_BROADCAST);
            intentFilter.addAction(Constant.CHANGE_MAC_STATE_BROADCAST);
            LocalBroadcastManager.getInstance(this).registerReceiver(receiveWatchInfo,intentFilter);
        }
        connectService();
        dataBinding.unbindWatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainService != null && isConnect) {
                    mainService.unbindWatch();
                }
            }
        });
        dataBinding.modeOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainService != null && isConnect) {
                    mainService.entryOrExitMode(true);
                }
            }
        });

        dataBinding.modeExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainService != null && isConnect) {
                    mainService.entryOrExitMode(false);
                }
            }
        });
        dataBinding.crashInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect) {
                    return;
                }
                EABleReadDebug eaBleReadDebug = new EABleReadDebug();
                eaBleReadDebug.setType(EABleReadDebug.DebugType.error_log);
                printLog(eaBleReadDebug);
            }
        });
        dataBinding.crashDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect) {
                    return;
                }
                EABleReadDebug eaBleReadDebug = new EABleReadDebug();
                eaBleReadDebug.setType(EABleReadDebug.DebugType.error_debug);
                printLog(eaBleReadDebug);
            }
        });
        dataBinding.memoryInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect) {
                    return;
                }
                if (TextUtils.isEmpty(dataBinding.memoryMac.getText().toString()) || TextUtils.isEmpty(dataBinding.macLen.getText().toString())) {
                    ShowToast.show(MainActivity.this, getString(R.string.command_prompt));
                    return;
                }
                EABleReadDebug eaBleReadDebug = new EABleReadDebug();
                eaBleReadDebug.setType(EABleReadDebug.DebugType.mem_log);
                eaBleReadDebug.setMem_addr(Integer.parseInt(dataBinding.memoryMac.getText().toString()));
                eaBleReadDebug.setMem_data_len(Integer.parseInt(dataBinding.macLen.getText().toString()));
                printLog(eaBleReadDebug);

            }
        });
        dataBinding.contentCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String log = dataBinding.logContent.getText().toString();
                if (TextUtils.isEmpty(log)) {
                    return;
                }
                ClipData clipData = ClipData.newPlainText(getString(R.string.app_name), log);
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(clipData);
            }
        });
        dataBinding.otaVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 if (TextUtils.isEmpty(dataBinding.watchName.getText().toString())) {
                 ShowToast.show(MainActivity.this, "请连接手表");
                 return;
                 }
                 */
                startActivity(new Intent(MainActivity.this, OtaListActivity.class));

            }
        });
        dataBinding.testData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, TestDataActivity.class));
            }
        });
        dataBinding.changeMac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect) {
                    return;
                }
                if (changeMacDialog == null) {
                    changeMacDialog = new ChangeMacDialog(MainActivity.this, new OnPositiveClickListener<String>() {
                        @Override
                        public void clickButton(String mac) {
                            if (mainService != null && isConnect) {
                                mainService.changeMac(mac);
                            }
                        }
                    });
                }
                changeMacDialog.show();

            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        String[] pages = getResources().getStringArray(R.array.function_page);
        dataBinding.slideLeft.setLayoutManager(linearLayoutManager);
        adapterPagesList = new AdapterPagesList(pages, MainActivity.this);
        dataBinding.slideLeft.setAdapter(adapterPagesList);
        dataBinding.slide.setShadowResourceLeft(R.mipmap.shadow);


    }

    private void printLog(EABleReadDebug eaBleReadDebug) {
        if (eaBleReadDebug == null) {
            return;
        }
        if (logContent == null) {
            logContent = new LogContent();
        }
        if (mainService != null && isConnect) {
            mainService.printLog(eaBleReadDebug, logContent);
        }
    }

    class LogContent implements DeviceBugCallback {

        @Override
        public void debugInfo(EABleReadDebug eaBleReadDebug) {
            Log.e(TAG, "获取到调试信息");
            if (eaBleReadDebug != null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(eaBleReadDebug.getLog())) {
                            dataBinding.logContent.setText(eaBleReadDebug.getLog());
                        } else {
                            dataBinding.logContent.setText(null);
                            ShowToast.show(MainActivity.this, getString(R.string.log_hint));
                        }
                    }
                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ShowToast.show(MainActivity.this, getString(R.string.log_hint));
                        dataBinding.logContent.setText(null);
                    }
                });
            }

        }

        @Override
        public void mutualFail(int i) {
            Log.e(TAG, "获取调试信息失败");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dataBinding.logContent.setText(null);
                    ShowToast.show(MainActivity.this, getString(R.string.log_fail));
                }
            });

        }
    }

    private void connectService() {
        sconnection = new ServiceConnection() {
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i("activity---->", "已断开Service");
                mainService = null;
            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub
                mainService = ((BluetoothService.MyBinder) service).getService();
            }

        };
        Intent intent = new Intent(MainActivity.this, BluetoothService.class);
        bindService(intent, sconnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        isResume = true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            if (!PermissionUtils.checkStoragePermission(MainActivity.this)) {
                PermissionUtils.requestStoragePermission(MainActivity.this);
            } else {
                FileUtils.createDir(MainActivity.this);
            }
        } else {
            if (checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_MEDIA_IMAGES}, 0x82);
            } else {
                FileUtils.createDir(MainActivity.this);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x01) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                FileUtils.createDir(MainActivity.this);
            }
        } else if (requestCode == 0x02) {
            boolean isPermission = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    isPermission = false;
                    break;
                }
            }
            if (!isPermission) {
                ShowToast.show(MainActivity.this, getString(R.string.location_permission));
            } else {
                Log.e(TAG, "跳转到扫描界面");
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
                    startActivity(new Intent(MainActivity.this, QRActivity.class));
                } else {
                    if (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN}, 0x80);
                    }else{
                        if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)!=PackageManager.PERMISSION_GRANTED){
                            requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT},0x81);
                        }else{
                            startActivity(new Intent(MainActivity.this, QRActivity.class));
                        }
                    }
                }
            }
        } else if (requestCode == 0x82) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                FileUtils.createDir(MainActivity.this);
            }
        }else if (requestCode==0x80){
            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)!=PackageManager.PERMISSION_GRANTED){
                    requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT},0x81);
                }else{
                    startActivity(new Intent(MainActivity.this, QRActivity.class));
                }
            }
        }else if (requestCode==0x81){
            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                startActivity(new Intent(MainActivity.this, QRActivity.class));
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    @Override
    protected void onDestroy() {
        if (receiveWatchInfo != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiveWatchInfo);
            receiveWatchInfo = null;
        }
        if (adapterPagesList != null) {
            adapterPagesList.destroyAdapter();
            adapterPagesList = null;
        }
        if (dataBinding != null) {
            dataBinding.unbind();
            dataBinding = null;
        }
        if (changeMacDialog != null) {
            changeMacDialog.destroyDialog();
            changeMacDialog = null;
        }
        if (sconnection != null) {
            unbindService(sconnection);
            sconnection = null;
        }
        super.onDestroy();
    }


    class ReceiveWatchInfo extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                if (action.equalsIgnoreCase(Constant.CONNECT_BROADCAST)) {
                    Device device = (Device) intent.getSerializableExtra("watch_info");
                    dataBinding.watchName.setText(device.getNameTxt());
                    dataBinding.tagName.setText(device.getTagTxt());
                    Log.i(TAG,"收到蓝牙连接广播");
                    if (mainService != null) {
                        mainService.connectWatch(device.getAddressTxt());
                    }

                } else if (action.equalsIgnoreCase(Constant.CONNECT_STATE_BROADCAST)) {
                    boolean state = intent.getBooleanExtra("connect_state", false);
                    if (state) {
                        dataBinding.bindState.setText(getString(R.string.bound));
                        dataBinding.scanBlue.setVisibility(View.GONE);
                        isConnect = true;
                    } else {
                        dataBinding.watchName.setText(null);
                        dataBinding.tagName.setText(null);
                        dataBinding.bindState.setText(null);
                        dataBinding.scanBlue.setVisibility(View.VISIBLE);
                        isResume = false;
                        if (isResume) {
                            ShowToast.show(MainActivity.this, getString(R.string.BLE_disconnect));
                        }


                    }
                } else if (action.equalsIgnoreCase(Constant.UNBIND_BROADCAST)) {
                    boolean state = intent.getBooleanExtra("unbind_state", false);
                    if (state) {
                        dataBinding.scanBlue.setVisibility(View.VISIBLE);
                        dataBinding.watchName.setText(null);
                        dataBinding.tagName.setText(null);
                        dataBinding.bindState.setText(null);
                        isConnect = false;
                    } else {
                        ShowToast.show(MainActivity.this, getString(R.string.unbinding_failed));
                    }
                } else if (action.equalsIgnoreCase(Constant.ENTRY_TEST_STATE_BROADCAST)) {
                    boolean state = intent.getBooleanExtra("result_state", false);
                    if (state) {
                        ShowToast.show(MainActivity.this, getString(R.string.enter_factory_test_mode));
                    } else {
                        ShowToast.show(MainActivity.this, getString(R.string.failed_to_enter_factory_test_mode));
                    }
                } else if (action.equalsIgnoreCase(Constant.EXIT_TEST_STATE_BROADCAST)) {
                    boolean state = intent.getBooleanExtra("result_state", false);
                    if (state) {
                        ShowToast.show(MainActivity.this, getString(R.string.exit_factory_test_mode));
                    } else {
                        ShowToast.show(MainActivity.this, getString(R.string.failed_to_exit_factory_test_mode));
                    }
                } else if (action.equalsIgnoreCase(Constant.CHANGE_MAC_STATE_BROADCAST)) {
                    boolean state = intent.getBooleanExtra("result_state", false);
                    if (state) {
                        ShowToast.show(MainActivity.this, getString(R.string.change_success));
                    } else {
                        ShowToast.show(MainActivity.this, getString(R.string.change_fail));
                    }
                }
            }
        }
    }
}